package com.finger.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.finger.common.to.es.SkuEsModel;
import com.finger.gulimall.search.config.GulimallSearchConfig;
import com.finger.gulimall.search.constant.ProductSearchConstant;
import com.finger.gulimall.search.service.ProductSaveService;
import lombok.extern.log4j.Log4j2;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Log4j2
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {

        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            // 创建数据库索引请求
            IndexRequest indexRequest = new IndexRequest();
            // 是个照顾索引
            indexRequest.index(ProductSearchConstant.PRODUCT_INDEX);
            // 指定文档id
            indexRequest.id(skuEsModel.getSkuId().toString());
            // 把需要上传得文件转换成json字符串
            String sourceString = JSON.toJSONString(skuEsModel);
            log.info(sourceString);
            // 指定资源
            indexRequest.source(sourceString, XContentType.JSON);
            // 添加请求
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulkResp = client.bulk(bulkRequest, GulimallSearchConfig.COMMON_OPTIONS);

        boolean b = bulkResp.hasFailures();

        return b;
    }
}
